//
//  SJZHomePageViewController.m
//  SJZBusiness
//
//  Created by 彭利民 on 2018/4/26.
//  Copyright © 2018年 bwton. All rights reserved.
//

#import "SJZHomePageViewController.h"
#import "SJZCouponCell.h"
#import "SJZScanCodeController.h"
#import "SJZCouponModel.h"
#import "SJZHexiaoFailureViewController.h"
#import "SJZHexiaoSuccessViewController.h"
#import "SJZLoginQuickViewController.h"
#import "SJZNavigationController.h"
#import "YQLHttpHandler.h"


@interface SJZHomePageViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) IBOutlet UITextField *couponCodeTextField;
@property (strong, nonatomic) IBOutlet UIView *topBarView;
@property (strong, nonatomic) IBOutlet UITableView *couponTableView;
@property (nonatomic, strong) NSMutableArray *couponArray;
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation SJZHomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.fd_prefersNavigationBarHidden = YES;
    [self configUI];
    
    [self.couponTableView.mj_header beginRefreshing];
    self.edgesForExtendedLayout = UIRectEdgeNone;

}



- (void)configUI{
    
    self.topBarView.frame = CGRectMake(0, -kNaviHeight - 20, kScreenWidth, kNaviHeight + 20);
    
    UILabel *paddingLb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kAutoWidth(10), 25)];
    paddingLb.textColor = [UIColor darkGrayColor];
    paddingLb.backgroundColor = [UIColor clearColor];
    self.couponCodeTextField.leftView = paddingLb;
    self.couponCodeTextField.leftViewMode = UITextFieldViewModeAlways;//必不可少
 
    self.couponTableView.delegate = self;
    self.couponTableView.dataSource = self;
    self.couponTableView.separatorStyle = NO;
    //下拉刷新
    self.couponTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.currentPage = 1;
        [self loadDataWithPage:1 length:20];
    }];
    
    //上拉加载
    self.couponTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.currentPage ++;
        [self loadDataWithPage:self.currentPage length:20];
    }];
}


- (IBAction)scanCouponCodeAction:(UIButton *)sender {
    
    SJZScanCodeController *scanCodeController = [[SJZScanCodeController alloc] init];
    scanCodeController.scanSuccessBlock = ^(NSString *result) {
        self.couponCodeTextField.text = result;
    };
    [self.navigationController pushViewController:scanCodeController animated:YES];
    
}

- (IBAction)consumerVoucode:(UIButton *)sender {
    
    [self.view endEditing:YES];
    
    if (self.couponCodeTextField.text.length < 5) {
        [MBProgressHUD showErrorMessage:@"请填写正确的兑换券"];
        return;
    }
    
    [self consumeVoucherWhit:self.couponCodeTextField.text];
    
    
}


- (void)loadDataWithPage:(NSInteger)currentPage length:(NSInteger)length{
    
    [YQLHttpHandler listConsumeVoucherWithuserId:[SJZAccountModel userFromArachiver].userId page:[NSString stringWithFormat:@"%ld",currentPage] length:[NSString stringWithFormat:@"%ld",length] voucherCode:@"" completion:^(NSArray *voucherArray, NSString *errStr) {
        if (!errStr.length) {

            if (self.currentPage == 1) {
                [self.couponArray removeAllObjects];
            }
            
            if (voucherArray.count == length) {
                [self.couponArray addObjectsFromArray:voucherArray];
                [self.couponTableView reloadData];
                [self.couponTableView.mj_footer endRefreshing];

            }else{
                [self.couponArray addObjectsFromArray:voucherArray];
                [self.couponTableView reloadData];
                [self.couponTableView.mj_footer endRefreshingWithNoMoreData];

            }
        }else{
            [self.couponTableView.mj_footer endRefreshing];
        }
        [self.couponTableView.mj_header endRefreshing];

    }];
    
}


//核销
- (void)consumeVoucherWhit:(NSString *)voucherCode{
    
    [MBProgressHUD showProgressMessageInView:@""];
    [YQLHttpHandler consumeVoucherWithuserId:[SJZAccountModel userFromArachiver].userId voucherCode:voucherCode completion:^(SJZCouponModel *couponModel, NSString *errStr) {
        [MBProgressHUD hideHUD];
        if (!errStr.length) {
            [self.couponTableView.mj_header beginRefreshing];
            SJZHexiaoSuccessViewController *successController = [[SJZHexiaoSuccessViewController alloc] init];
            successController.couponModel = couponModel;
            [self.navigationController pushViewController:successController animated:YES];
        }else{
            [MBProgressHUD showErrorMessage:errStr];
        }
    }];
    
    
    
//    SJZAccountModel *accountModel = [SJZAccountModel userFromArachiver];
//    self.currentPage ++;
//    NSString *urlString = [NSString stringWithFormat:@"%@SJZMetroApi/api/merchant/consumeVoucher",kDominUrl];
//    NSDictionary *paramDict = @{
//                                @"merchantId":accountModel.userId,
//                                @"token":accountModel.token,
//                                @"voucherCode":[voucherCode removeWhiteSpacesFromString]
//                                };
//    [MBProgressHUD showProgressMessageInWindow:@"加载中"];
//    [[SJZAFNSessionManager sharedSJZAFNSessionManager] POST:urlString parameters:paramDict success:^(id SuccessResponse) {
//        [MBProgressHUD hideHUD];
//        NSDictionary *successDict = [NSDictionary dictionaryWithDictionary:SuccessResponse];
//
//        if ([successDict[kResultCode] isEqualToString:@"0000"]) {
//            [self.couponTableView.mj_header beginRefreshing];
//            SJZHexiaoSuccessViewController *successController = [[SJZHexiaoSuccessViewController alloc] init];
//            successController.successDict = successDict;
//            [self.navigationController pushViewController:successController animated:YES];
//
//        }else if ([successDict[kResultCode] isEqualToString:@"0006"]){
//            [MBProgressHUD showTipMessage:successDict[kResultDesc]];
//            [SJZAccountModel saveUserObjectWithUser:nil];
//            [[NSNotificationCenter defaultCenter] postNotificationName:kLoginStatusChange object:nil];
//
//        }else{
//
//            SJZHexiaoFailureViewController *failController = [[SJZHexiaoFailureViewController alloc] init];
//            [self.navigationController pushViewController:failController animated:YES];
//            failController.fail = successDict[kResultDesc];
//
//        }
//
//    } failure:^(NSError *error) {
//        [MBProgressHUD hideHUD];
//        [MBProgressHUD showErrorMessage:@"核销失败，请稍后重试"];
//
//    }];
    
}



#pragma mark - TableViewDelegate DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.couponArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SJZCouponCell *couponCell = [SJZCouponCell cellWithTableView:tableView indexPath:indexPath];
    couponCell.couponModel = self.couponArray[indexPath.row];
    return couponCell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 40;
    
}


- (void)leftItemClick
{
    NSLog(@"统计点击");
    
}

#pragma mark - lazyLoad
- (NSMutableArray *)couponArray{
    
    if (_couponArray == nil) {
        _couponArray = [NSMutableArray array];
    }
    
    return _couponArray;
}



@end
